package com.common.library.data;

import java.util.ArrayList;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;

import com.common.library.util.Helper;
import com.common.library.util.LogUtil;
import com.common.library.util.NetworkHelper;

/**
 * 
 * function: Get请求：没有提示信息的事件处理: 用来即使报错也没关系的数据请求处理
 *
 * @author  aXiBa
 */
public class EventHandler2Get extends CommonEventHandler {
	
	private static final String TAG = EventHandler2Get.class.getSimpleName();
	
	
	public EventHandler2Get(String url, String useragent1, ResultHandlerInEvent resultHandler) {
		
		this.url = url;
		this.useragent1 = useragent1;
		this.resultHandler = resultHandler;
		
		execRequest();
	}

	
	public EventHandler2Get(String url, ArrayList<NameValuePair> params, String useragent1, ResultHandlerInEvent resultHandler) {
		
		this.url = url;
		this.params = params;
		this.useragent1 = useragent1;
		this.resultHandler = resultHandler;
		
		execRequest();
	}
	
	
	public EventHandler2Get(String url, String useragent1, ResultHandlerInEvent resultHandler, boolean isEncrypt) {
		
		this.url = url;
		this.useragent1 = useragent1;
		this.resultHandler = resultHandler;
		this.isEncrypt = isEncrypt;
		
		execRequest();
	}
	
	public EventHandler2Get(String url, ArrayList<NameValuePair> params, String useragent1, ResultHandlerInEvent resultHandler, boolean isEncrypt) {
		
		this.url = url;
		this.params = params;
		this.useragent1 = useragent1;
		this.resultHandler = resultHandler;
		this.isEncrypt = isEncrypt;
		
		execRequest();
	}
	
	
	@Override
	public HttpResponse doRequest() throws Exception {
		
		String urlStr = getUrl(url, params);
		LogUtil.i(TAG, urlStr);
		return NetworkHelper.sendHttpGetString(urlStr, useragent1);
	}
	
	
	// 拼接url
	private String getUrl(String url, ArrayList<NameValuePair> paramsList) {
		
		StringBuffer result = new StringBuffer();
		result.append(url);
		
		if(Helper.isNotEmpty(params)) {
			for (NameValuePair pair : paramsList) {
				if (Helper.isNotNull(pair)){
					if(result.toString().contains("?")) {
						result.append("&");
						result.append(pair.getName());
						result.append("=");
						result.append(pair.getValue());
					}
					else {
						result.append("?");
						result.append(pair.getName());
						result.append("=");
						result.append(pair.getValue());
					}
				}
			}
		}
		
		return result.toString();
	}
	
}
